package com.cn.kehong.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.IDepartmentService;
import com.cn.kehong.api.ILoginService;
import com.cn.kehong.api.IRoleService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.domain.Department;
import com.cn.kehong.domain.Login;
import com.cn.kehong.domain.Role;
import com.cn.kehong.domain.SysItem;
import com.cn.kehong.utils.*;
import com.sun.deploy.nativesandbox.comm.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @类名:LoginController
 * @包名:com.cn.kehong.controller
 * @作者:chenxingliang
 * @时间:2022-11-13 09:17
 * @版本:1.0.0
 */

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILoginService loginService;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    private static final String MOBILE_REGEX = "^1[3-9]\\d{9}$";

    @Autowired
    private Config config;

    @ResponseBody
    @RequestMapping("/getLoginList/{frontToken}")
    public JsonResponse<List<Login>> getLoginList(QueryForm queryForm,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getLoginList(queryForm);
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/getLoginSelectList/{frontToken}")
    public JsonResponse<List<Login>> getLoginSelectList(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getLoginSelectList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/getLoginAndRoleSelectList/{frontToken}")
    public JsonResponse<List<Login>> getLoginAndRoleSelectList(@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> loginResult = loginService.getLoginAndRoleSelectList();
        response.setResult(loginResult);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/addLogin/{frontToken}")
    public JsonResponse<String> addLogin(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.addLoginDetail(login);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/updateLogin/{frontToken}")
    public JsonResponse<String> updateLogin(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.updateLoginDetail(login);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/delLogin/{frontToken}")
    public JsonResponse<String> delLogin(@RequestBody QueryForm queryForm, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.delLoginDetail(queryForm);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/updatePassword/{frontToken}")
    public JsonResponse<String> updatePassword(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.updatePassword(login);
        return CommonUtil.getResponseData(response,result);
    }


    @ResponseBody
    @RequestMapping("/doLogin")
    public JsonResponse<Login> doLogin(Login login,HttpServletRequest httpServletRequest) throws Exception {
        JsonResponse<Login> response = new JsonResponse<Login>();
        String expireOpen = config.expireOpen;
        if(!StringUtils.equals("1",expireOpen)){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(new Date().getTime() > simpleDateFormat.parse("2025-02-20 00:00:00").getTime()){
                response.setSuccess(false);
                response.setMessage("系统已经过期");
                return response;
            }
        }
        String ip = httpServletRequest.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip)||"unknown".equalsIgnoreCase(ip)) {
            ip =  httpServletRequest.getRemoteAddr();
        }
        System.out.println("=============ip================:"+ip);
        String macAddress = NetworkUtil.getMacAddressByIp(ip);
        System.out.println("=============macAddress================:"+macAddress);
        Login result = loginService.doLogin(login);
        response.setSuccess(StringUtils.isEmpty(result.getMessage())?true:false);
        response.setResult(result);
        return response;
    }


    @ResponseBody
    @RequestMapping("/getLoginDetail/{frontToken}")
    public JsonResponse<String> getLoginDetail(Login login,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.getLoginDetail(login);
        return CommonUtil.getResponseData(response,result);
    }

    @ResponseBody
    @RequestMapping("/loginOut")
    public JsonResponse<String> loginOut(HttpServletRequest httpServletRequest) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String sessionId = httpServletRequest.getSession().getId();
        redisTemplate.delete(sessionId);
        response.setSuccess(true);
        return response;
    }

    /**
     * 更新token
     */

    @ResponseBody
    @RequestMapping("/getRefreshToken")
    public JsonResponse<Login> getRefreshToken() throws Exception {
        JsonResponse<Login> response = new JsonResponse<Login>();
        String sessionId = httpServletRequest.getSession().getId();
        String token = (String) redisTemplate.opsForValue().get(sessionId);
        Login login = new Login();
        login.setToken(token);
        JSONObject jsonObject = JSONObject.parseObject(MD5Util.getDecoder(token));
        login.setId(jsonObject.getString("id"));
        login.setUserAccount(jsonObject.getString("userAccount"));
        login.setUserName(jsonObject.getString("userName"));
        login.setAccountType(jsonObject.getString("accountType"));
        response.setResult(login);
        response.setSuccess(true);
        return response;
    }

    @ResponseBody
    @RequestMapping("/api/doLoginByPhone")
    public JsonResponse<Login> doLoginByPhone(String  user, String password,String code) throws Exception {
        JsonResponse<Login> response = new JsonResponse<Login>();
        Login result = loginService.doLoginByPhone(user,password,code);
        response.setResult(result);
        response.setSuccess(StringUtils.isEmpty(result.getMessage())?true:false);
        return response;
    }

    @ResponseBody
    @RequestMapping("/api/sendCode")
    public JsonResponse<String> sendCode(@RequestParam(value = "phone", required = true) String phone) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.sendCode(phone);
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    //获取操作工名称
    @ResponseBody
    @RequestMapping("/api/getLoginNameByWorkNum")
    public JsonResponse<String> getLoginNameByWorkNum(@RequestParam(value = "workNum", required = true) String workNum) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        String result = loginService.getLoginNameByWorkNum(workNum);
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    //获取料原人名称
    @ResponseBody
    @RequestMapping("/api/getLoginLiaoYuan")
    public JsonResponse<List<Login>> getLoginLiaoYuan() throws Exception {
        JsonResponse<List<Login>> response = new JsonResponse<List<Login>>();
        List<Login> result = loginService.getLoginLiaoYuan();
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    //用户模版下载
    @ResponseBody
    @RequestMapping("/downloadLoginTempFile")
    public void downloadDeviceTempFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/");
        String fileName = path + "login.xlsx";
        this.downloadFile(fileName,response);
    }


    public void downloadFile(String path, HttpServletResponse response) throws Exception {
        String name = StringUtils.isNotBlank(path)?path:"";
        name = URLDecoder.decode(name,"utf-8");
        name = new String(name.getBytes("ISO-8859-1"),"utf-8");
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(name);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            closeInputStream(is);
            closeOutputStream(os);
        }
    }

    private static void closeInputStream(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void closeOutputStream(OutputStream os) {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //用户模版导入
    @ResponseBody
    @RequestMapping("/importTempFile")
    public JsonResponse<String> importTempFile(@RequestParam(value = "multipartFile", required = true)  MultipartFile multipartFile, @RequestParam(value ="notToken", required = true) String notToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        DataFormatter formatter = new DataFormatter();

        try{
            InputStream is=multipartFile.getInputStream();
            XSSFWorkbook wb=new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0); // 获取第一个工作表
            XSSFRow row=null;
            XSSFCell cell=null;
            Login login=null;
            List<Login> loginArrayList=new ArrayList<>();
            int num=1;
            for (int i=1;i<=sheet.getLastRowNum();i++){
                row=sheet.getRow(i);
                login = new Login();
                String id = CommonUtil.generateRandomNum("login-");
                login.setId(id);
                login.setType("0");
                login.setAccountStatus("0");
                login.setLoginStatus("0");
                login.setStatus("0");
                login.setAppUser("0");
                login.setAppUserType("0");
                login.setCreateTime(new Date());
                login.setUpdateTime(new Date());
                for (int j=0;j<row.getLastCellNum();j++){
                    cell=row.getCell(j);
                    String cellValue = formatter.formatCellValue(cell);
                    if (j==0){
                        List<Department> department=departmentService.getIdBydeptName(cellValue);
                        if (department.size()==0){
                            response.setMessage("第"+num+"行"+"部门不存在，请检查部门");
                            return response;
                        }else {
                            login.setDeptId(department.get(0).getId());
                        }
                    }else if (j==1){
                        List<Role> roles=roleService.getIdByRoleName(cellValue);
                        if (roles.size()==0){
                            response.setMessage("第"+num+"行"+"角色不存在，请检查角色");
                            return response;
                        }else {
                            login.setRoleId(roles.get(0).getId());
                        }
                    }else if(j==2){
                        login.setUserName(cellValue);
                    }else if(j==3){
                        login.setUserAccount(cellValue);
                    }else if (j==4){
//                        if (!Pattern.matches(MOBILE_REGEX, cellValue)){
//                            response.setMessage("第"+num+"行"+"手机号不正确");
//                            return response;
//                        }else {
                            login.setPhone(cellValue);
//                        }
                    }else if (j==5){
                        login.setWorkNum(cellValue);
                    }else if (j==6){
                        login.setPassword(MD5Util.MD5(cellValue));
//                        login.setPassword(cellValue);
                    }else if (j==7){
                        if (cellValue.equals("16-1")||cellValue.equals("16-2")){
                            login.setGroupName(cellValue);
                        }else {
                            response.setMessage("第"+num+"行"+"车间不存在，请检查车间");
                            return response;
                        }
                    }else if (j==8){
                        if (cellValue.equals("质量")){
                            login.setAppUserType("1");
                        }else if (cellValue.equals("生产")){
                            login.setAppUserType("0");
                        }else {
                            response.setMessage("第"+num+"行"+"送检角色不存在，请检查送检角色");
                            return response;
                        }
                    }else if (j==9){
                        if (cellValue == null || cellValue.trim().isEmpty()) {
                            response.setMessage("第" + num + "行用户类型为空，请检查用户类型");
                            return response;
                        }
                        String[] values = cellValue.split(",");
                        List<String> userTypes = new ArrayList<>();
                        for (String value : values) {
                            value = value.trim();
                            if (value.equals("品控")) {
                                userTypes.add("1");
                            } else if (value.equals("生产")) {
                                userTypes.add("2");
                            } else if (value.equals("确认")) {
                                userTypes.add("3");
                            }
                        }
                        if (userTypes.isEmpty()) {
                            response.setMessage("第" + num + "行用户类型不存在，请检查用户类型");
                            return response;
                        }

                        String appUserStr = String.join(",", userTypes);
                        login.setAppUser(appUserStr);
                    }
                    }
                loginArrayList.add(login);
                num++;
            }
            int ret=loginService.batchLoginList(loginArrayList);
            if (ret!=0){
                response.setSuccess(true);
                return response;
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setMessage("系统忙，请稍后重试....");
        }
        return response;
    }

}
